#include "mainwindowimpl.h"
#include <QDebug>
#include "signaldata.h"
//
MainWindowImpl::MainWindowImpl( QWidget * parent, Qt::WFlags f) 
	: QMainWindow(parent, f)
{
	setupUi(this);
        setSerialComboBox();

        //TODO PARA METER EL PLOT
        const double intervalLength = 59.0 - QTime::currentTime().second(); // seconds
        d_plot = new Plot(this->plotFrame);
        d_plot->setIntervalLength(intervalLength);
        QHBoxLayout *layout = new QHBoxLayout(this->plotFrame);
        layout->addWidget(d_plot,10);

        //pone color de fondo del layer a rojo
        QPalette p(connectLayer->palette());
        p.setColor(QPalette::Base,Qt::red);
        connectLayer->setPalette(p);

        //pone color de fondo del layer a gris
        QPalette p2(aireStateLabel->palette());
        p2.setColor(QPalette::Base,Qt::gray);
        aireStateLabel->setPalette(p2);

        //actualizar todas las temperaturas
        tSetSpinBox->setValue(d_plot->getTSet());
        tRangeSpinBox->setValue(d_plot->getTRange());

        //actualiza la configuracion del puerto serie desde archivo
        if(configFile.existPortConfig()){
            QPair<QString, QString> portSetting = configFile.getPortConfig();
            portComboBox->setCurrentIndex(portComboBox->findText(portSetting.first));
            speedCommComboBox->setCurrentIndex(speedCommComboBox->findText(portSetting.second));
        }



        //TODOS LOS CONNECT
        connect(qport,SIGNAL(newData(QByteArray)),this,SLOT(received(QByteArray)));
        //connect(&serial, SIGNAL(lineReceived(QString)), this, SLOT(parseLineReceived(QString)));
        connect(tSetSpinBox, SIGNAL(valueChanged(double)), d_plot, SLOT(setTSet(double)));
        connect(tRangeSpinBox, SIGNAL(valueChanged(double)), d_plot, SLOT(setTRange(double)));
        connect(this, SIGNAL(tempReceived(double)), this, SLOT(refreshLCDTemp(double)));
        connect(this, SIGNAL(tempReceived(double)), this, SLOT(addTempToPlot(double)));
        connect(this, SIGNAL(textToLog(QString)), this, SLOT(logAppend(QString)));
        connect(this, SIGNAL(aireStateReceived(int)), this, SLOT(aireStateChange(int)));
        connect(this, SIGNAL(alarmStateReceived(int)), this, SLOT(alarmStateChange(int)));

}

void MainWindowImpl::on_openCloseButton_clicked(){
   /* if(){
        //serial.close();

        openCloseButton->setText("Conectar");
        connectLayer->setText("DESCONECTADO");
        //pone color de fondo del layer a rojo
        QPalette p(connectLayer->palette());
        p.setColor(QPalette::Base,Qt::red);
        connectLayer->setPalette(p);

        qDebug("Aprete para cerrar");
        d_plot->stop();

    }else{
        bool ok;
        qDebug() << "Port serial: " << portComboBox->currentText() << " , " << speedCommComboBox->currentText().toInt(&ok, 10);
        //serial.open(portComboBox->currentText(),speedCommComboBox->currentText().toInt(&ok, 10));

        //if(!serial.isOpen() || serial.errorStatus()) return;


        openCloseButton->setText("Desconectar");
        connectLayer->setText("CONECTADO");
        //pone color de fondo del layer a verde
        QPalette p(connectLayer->palette());
        p.setColor(QPalette::Base,Qt::green);
        connectLayer->setPalette(p);

        qDebug("Aprete para abrir");

        d_plot->start();

        //this->getConfigParameters();


    }*/
}

void MainWindowImpl::received(QByteArray Dato){
        logText->append(qport->FormatData(Dato,'t',""));
}

void MainWindowImpl::processData(){
    int bytesReceived = MySerialPort->bytesAvailable();
    QString dataReceived;
    char byte;

    for(int i=0; i<bytesReceived; i++){
       byte = MySerialPort->getNextByte();
       dataReceived.append(byte);
    }
}

void MainWindowImpl::parseLineReceived(QString dataReceived){
    qDebug() << dataReceived;

    //parseo de la informacion que esta enviando
    bool ok;
    double tSetReceived, tRangeReceived;
    int function = dataReceived.left(2).toInt(&ok,10);


    switch(function){
    case 1: //recibo temperatra sensada
        emit textToLog(dataReceived);
        dataReceived.replace(0,22,"");
        emit tempReceived(dataReceived.toDouble(&ok));
        break;
    case 2: //recibo tset y trange
        dataReceived.remove("02-Tset:");
        tSetReceived = dataReceived.left(5).toDouble(&ok);
        dataReceived.replace(0, 13, "");
        tRangeReceived = dataReceived.left(4).toDouble(&ok);
        emit configReceived(tSetReceived,tRangeReceived);
        break;
    case 3:
        dataReceived.remove("03-Aire_state:");
        emit aireStateReceived(dataReceived.toInt(&ok,10));
        break;
    case 4: //recibo alarm state
        dataReceived.remove("04-Alarm_state:");
        emit alarmStateReceived(dataReceived.toInt(&ok,10));
        break;
    //recepcion de ACK
    case 11:
        emit textToLog(">>> PARAMETROS DE CONFIGURACION SETEADOS CORRECTAMENTE");
        break;
    case 21:
        emit textToLog(">>> PARAMETROS DE CONFIGURACION RECIBIDOS DESDE DISPOSITIVO");
        break;
    default: break;
    }

}

void MainWindowImpl::setSerialComboBox(){

    //agrego hasta el puerto serie 2
    portComboBox->addItem("/dev/ttyS0",0);
    portComboBox->addItem("/dev/ttyS1",0);
    portComboBox->addItem("/dev/ttyS2",0);

    //agrega todas las velocidades posibles del puerto serie
    for(int i = 300; i<38401; i=2*i){
        std::string speedString = boost::lexical_cast<std::string>(i);
        speedCommComboBox->addItem(QString::fromStdString(speedString),0);
    }
    for(int i = 57600; i<115201; i=2*i){
        std::string speedString = boost::lexical_cast<std::string>(i);
        speedCommComboBox->addItem(QString::fromStdString(speedString),0);
    }

}

void MainWindowImpl::refreshLCDTemp(double value){
    tempNewLCD->display(value);
    if(value > d_plot->getTSet() + d_plot->getTRange()){
        //pone letra a rojo
        QPalette p(tempNewLCD->palette());
        p.setColor(QPalette::WindowText,Qt::red);
        tempNewLCD->setPalette(p);
    }else{
        //pone letra en negro
        QPalette p(tempNewLCD->palette());
        p.setColor(QPalette::WindowText,Qt::black);
        tempNewLCD->setPalette(p);
    }
}

void MainWindowImpl::addTempToPlot(double value){
    //manda temperatura al grafo
    const QPointF s(d_plot->getTimeFromMidnight(), value);
    SignalData::instance().append(s);
}

void MainWindowImpl::logAppend(QString txt){
    QString textToLog = QDate::currentDate().toString("dd/MM/yyyy - ");
    textToLog.append(QTime::currentTime().toString("HH:mm:ss - "));
    textToLog.append(txt);
    logText->append(textToLog);
}

void MainWindowImpl::getConfigParameters(){
    //serial.write("20-Parametros\r\n");
    emit textToLog("<<< PARAMETROS DE CONFIGURACION SOLICITADOS");
}

void MainWindowImpl::setConfigParameters(){
    QString paramSend;
    paramSend = QString("10-%1-%2\r\n").arg(tSetSpinBox->value()).arg(tRangeSpinBox->value());
    //serial.write(paramSend);

}

void MainWindowImpl::aireStateChange(int state){
    if(state == 0){
        aireStateLabel->setText("AIRE APAGADO");
        //pone color de fondo del layer a gris
        QPalette p(aireStateLabel->palette());
        p.setColor(QPalette::Base,Qt::gray);
        aireStateLabel->setPalette(p);
    }else if(state == 1){
        aireStateLabel->setText("AIRE ENCENDIDO");
        //pone color de fondo del layer a verde
        QPalette p(aireStateLabel->palette());
        p.setColor(QPalette::Base,Qt::green);
        aireStateLabel->setPalette(p);
    }
}

void MainWindowImpl::alarmStateChange(int state){
    if(state == 0){
        alarmCheckBox->setChecked(false);
    }else if(state == 1){
        alarmCheckBox->setChecked(true);
    }
}
//
